// 短文传输用websorket 长文传输用post
//纯图文 activeItem.type:11 
const onmessage = (activeItem, token) => {
	activeItem.createTime = getdate();
	let obj = {
		code: 200,
		type: 1, //1：message:2：relationship,3：online
		message: "charMsg",
		data: {}
	}
	let sendSuccess = {
		code: 200,
		type: 7,
		status: true,
		message: "success"
	}
	let sendError = {
		code: 200,
		type: 7,
		status: false,
		message: "error"
	}
	try {
		if (!activeItem.fromId || !activeItem.fromName || !activeItem.fromUrl || !activeItem.activeId ||  activeItem.isGroup === undefined ||activeItem.imagesUrl==undefined   ) {
			obj.message = "未按要求传参";
			obj.code = 201;
			throw new Error(obj.message);
		}
		let send = Object.assign(obj, {
			data: activeItem
		});
		send.data.message="[图片]"
		let type=11
		//添加消息
		let sql =
			`INSERT INTO message(\`Id\`, \`msg\`, \`userId\`, \`otherId\`, \`isGroup\`, \`status\`,\`type\`,\`imagesUrl\`, \`createTime\`, \`updateTime\`,\`dirimagesUrl\`,\`msglength\`) 
			VALUES (null, '[图片]', ${activeItem.fromId},${activeItem.activeId},${activeItem.isGroup},1,${activeItem.type},
			'${activeItem.imagesUrl}', '${activeItem.createTime}', '${activeItem.createTime}','','0')`;
		let paramsList = ["[图片]"];
		let lastMsg = "[图片]"
		//修改联系人最后一条信息的时间和信息
		let updateSQL = "";
		let updateSQLParams = [lastMsg];
		if (activeItem.isGroup === 1) {
			//群组 群发
			updateSQL =
				`update grouplastmsg set lastMessage=?,updateTime='${activeItem.createTime}' where groupId=${activeItem.activeId} and status=1`

			if (activeItem.activeId === 1 || activeItem.isneed === 1) {
				//id 1 为所有人必进的群 all推送
				// for (client in wsClients) {
				// 	wsClients[client].forEach((client) => {
				// 		client.send(JSON.stringify(send));
				// 	});
				// }
				WSsendAll(send)
				shsDB(sql).then(data => {
					try {
						upIntegral(activeItem.fromId, 1)
					} catch (e) {
						//TODO handle the exception
					}
					return shsDB(updateSQL, updateSQLParams)
				}).then(data => {
					sendMessage(activeItem.fromId,sendSuccess,token)
					// wsClients[activeItem.fromId].forEach((client) => {
					// 	if (client.wtoken === token) {
					// 		client.send(JSON.stringify(sendSuccess));
					// 	}
					// });
				}).catch(err => {
					console.log("err 信息添加", err);
					sendError.message = err.message;
					sendMessage(activeItem.fromId,sendError,token)
					// wsClients[activeItem.fromId].forEach((client) => {
					// 	if (client.wtoken === token) {
					// 		client.send(JSON.stringify(sendError));
					// 	}
					// });
				})
			} else {
				//法二：获取群人数再与online比较  
				// 看群人数大还是online人数大
				// online userCount大 按数据库循环online 反之则反
				let selectSql = `select userlist from  shsgroup where Id= ${activeItem.activeId} and status=1;`;
				shsDB(selectSql).then(data => {
					if (data.length === 0) {
						throw new Error("data.length===0");
					}
					if (data[0].userlist === undefined || data[0].userlist === null) {
						throw new Error("userlist is null");
					}
					let userlist = data[0].userlist.split(',');
					if (userlist.length - 1 < userCount) {
						for (let i = 0; i < userlist.length - 1; i++) {
							let userId = userlist[i];
							if (userId in wsClients) {
								wsClients[userId].forEach((client) => {
									client.send(JSON.stringify(send));
								});
							}
						}
					} else {
						for (client in wsClients) {
							if (userlist.includes(client.toString())) {
								wsClients[client].forEach((client) => {
									client.send(JSON.stringify(send));
								});
							}
						}
					}
					shsDB(sql).then(data => {
						try {
							upIntegral(activeItem.fromId, 1)
						} catch (e) {
							//TODO handle the exception
						}
						return shsDB(updateSQL, updateSQLParams)
					}).then(data => {
						// wsClients[activeItem.fromId].forEach((client) => {
						// 	client.send(JSON.stringify(sendSuccess));
						// });
						wsClients[activeItem.fromId].forEach((client) => {
							if (client.wtoken === token) {
								client.send(JSON.stringify(sendSuccess));
							}
						});
					}).catch(err => {
						console.log("err 信息添加", err);
						sendError.message = obj.message;
						// wsClients[activeItem.fromId].forEach((client) => {
						// 	client.send(JSON.stringify(sendError));
						// });
						wsClients[activeItem.fromId].forEach((client) => {
							if (client.wtoken === token) {
								client.send(JSON.stringify(sendError));
							}
						});
					})
				}).catch(err => {
					obj.code = 201;
					if (err.message === "userlist is null" || err.message === "data.length===0") {
						obj.message = "无法在封禁的群里发信息"
					} else {
						obj.message = err.message
						console.log("err 群消息推送", err)
					}
					sendError.message = obj.message;
					wsClients[activeItem.fromId].forEach((client) => {
						client.send(JSON.stringify(sendError));
					});
				})
			}
		} else {
			// 单发
			//发送者
			updateSQL =
				`update relationshipuser set lastMessage=?,updateTime='${activeItem.createTime}' where (userId=${activeItem.fromId} and otherId=${activeItem.activeId}) or (userId=${activeItem.activeId} and otherId=${activeItem.fromId}) and status=1`
			wsClients[activeItem.fromId].forEach((client) => {
				client.send(JSON.stringify(send));
			});
			//接收者
			if (wsClients[activeItem.activeId] !== undefined) {
				wsClients[activeItem.activeId].forEach((client) => {
					client.send(JSON.stringify(send));
				});
			}
			shsDB(sql).then(data => {
				try {
					upIntegral(activeItem.fromId, 1)
				} catch (e) {
					//TODO handle the exception
				}
				return shsDB(updateSQL, updateSQLParams)
			}).then(data => {
				wsClients[activeItem.fromId].forEach((client) => {
					client.send(JSON.stringify(sendSuccess));
				});
			}).catch(err => {
				console.log("err 信息添加", err);
				sendError.message = obj.message;
				wsClients[activeItem.fromId].forEach((client) => {
					client.send(JSON.stringify(sendError));
				});
			})
		}

	} catch (e) {
		//TODO handle the exception
		sendError.message = e.message;
		wsClients[activeItem.fromId].forEach((client) => {
			client.send(JSON.stringify(sendError));
		});
	}
}

module.exports = onmessage